package cn.kgc.ubagnet.security;

import cn.kgc.ubagnet.mapper.BuyerMapper;
import cn.kgc.ubagnet.pojo.Buyer;
import cn.kgc.ubagnet.pojo.BuyerExample;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shkstart
 * @create 2020-08-06 14:02
 */
@Service
public class CrowdUserDetailsService  implements UserDetailsService {
    @Resource
    BuyerMapper buyerMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        BuyerExample example=new BuyerExample();
        BuyerExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneEqualTo(s);
        List<Buyer> buyers = buyerMapper.selectByExample(example);
        if (buyers != null && buyers.size() > 0) {
            Buyer buyer = buyers.get(0);
            if (buyer == null) {
                return null;
            }

            //封装角色和权限信息
            List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ROLE_studnet", "ROLE_teacher");
            return new User(buyer.getPhone(), buyer.getPassword(), authorityList);
        }
        return null;
    }
}
